package dao_sys

import (
	"wrblog-api-go/app/model"
	"wrblog-api-go/app/model/model_sys"
	"wrblog-api-go/pkg/errs"
	"wrblog-api-go/pkg/mysql"
	"wrblog-api-go/pkg/utils"
)

func GetSysRolePageList(sysRole model_sys.SelectSysRole) (sysRoles []model_sys.SysRoleVo, total int64) {
	db := mysql.Db().Model(&model_sys.SysRolePo{})
	if sysRole.RoleName != "" {
		db = db.Where("role_name like ?", "%"+sysRole.RoleName+"%")
	}
	if sysRole.RoleKey != "" {
		db = db.Where("role_type like ?", "%"+sysRole.RoleKey+"%")
	}
	if sysRole.Status != "" {
		db = db.Where("status = ?", sysRole.Status)
	}
	if !sysRole.StartTime.IsZero() {
		db = db.Where("create_time >= ?", sysRole.StartTime)
	}
	if !sysRole.EndTime.IsZero() {
		db = db.Where("create_time <= ?", sysRole.EndTime)
	}
	db = db.Where("deleted = '0'").Count(&total).Order("role_sort").Order("create_time desc")
	if sysRole.PageNum != nil && sysRole.PageSize != nil {
		db = db.Limit(*sysRole.PageSize).Offset((*sysRole.PageNum - 1) * *sysRole.PageSize)
	} else {
		db = db.Limit(10)
	}
	err := db.Find(&sysRoles).Error
	err = errs.ErrNotFound(err)
	return
}

func GetSysRoleById(roleId int) (sysRole model_sys.SysRoleVo, err error) {
	db := mysql.Db().Model(&model_sys.SysRolePo{})
	err = db.Where("role_id = ? and deleted = '0'", roleId).First(&sysRole).Error
	err = errs.ErrNotFound(err)
	return
}

func AddSysRole(sysRole model_sys.SysRolePo) (int, error) {
	err := mysql.Db().Create(&sysRole).Error
	return sysRole.RoleId, errs.ErrNotFound(err)
}

func EditSysRole(sysRole model_sys.SysRolePo) (int64, error) {
	res := mysql.Db().Updates(&sysRole)
	return res.RowsAffected, errs.ErrNotFound(res.Error)
}

func RemoveSysRole(roleIds []string, uk string) (int64, error) {
	db := mysql.Db().Model(&model_sys.SysRolePo{}).Where("role_id in (?)", roleIds)
	res := db.Updates(&model_sys.SysRolePo{BaseEntity: model.BaseEntity{UpdateTime: utils.NewTimeNow(), UpdateBy: uk, Deleted: "1"}})
	return res.RowsAffected, errs.ErrNotFound(res.Error)
}

func DeleteSysRole(roleIds []string) (int64, error) {
	db := mysql.Db().Model(&model_sys.SysRolePo{})
	res := db.Delete(&model_sys.SysRolePo{}, roleIds)
	return res.RowsAffected, errs.ErrNotFound(res.Error)
}

func GetRolesByUserId(userId int64) (sysRoles []model_sys.SysRoleVo, err error) {
	db := mysql.Db().Model(&model_sys.SysRolePo{}).
		Table("sys_role sr").Select("sr.*").
		Joins("inner join sys_user_role sur on sur.role_id = sr.role_id")
	err = db.Where("sur.user_id = ? and sr.deleted = '0'", userId).First(&sysRoles).Error
	err = errs.ErrNotFound(err)
	return
}
